package com.antong.cloud.common.security.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.antong.cloud.common.core.util.R;
import com.antong.cloud.common.security.component.PermitAllUrlProperties;
import com.antong.cloud.common.security.token.JwtUserAuthenticationConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.HttpStatus;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.DefaultAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 资源服务器配置
 */
@Configuration
@EnableResourceServer
//@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableConfigurationProperties(PermitAllUrlProperties.class)
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    @Autowired
    private PermitAllUrlProperties permitAllUrl;

    /**
     * 远程验证令牌
     * @return
     */
    /*@Bean
    public RemoteTokenServices tokenService() {
        RemoteTokenServices tokenService = new RemoteTokenServices();
        tokenService.setClientId("client01");
        tokenService.setClientSecret("client01_secret");
        tokenService.setCheckTokenEndpointUrl("http://localhost:9000/oauth/check_token");
        return tokenService;
    }*/


    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.tokenServices(tokenService())
        .authenticationEntryPoint(new AuthenticationEntryPoint() {
            @Override
            public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
                R result = null;
                Throwable cause = e.getCause();
                response.setStatus(HttpStatus.OK.value());
                response.setHeader("Content-Type", "application/json;charset=UTF-8");
                try {
                    if(cause instanceof InvalidTokenException) {
                        result = R.fail(null, "认证失败,无效或过期token");

                    }else{
                        result = R.fail(null, "认证失败,没有携带token");
                    }
                    response.getWriter().write(new ObjectMapper().writeValueAsString(result));
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        })
        .stateless(true);//无状态模式
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        // SessionCreationPolicy.STATELESS模式： Spring Security不会创建session，或使用session
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and().csrf().disable();
        ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry registry = http
                .authorizeRequests();
        permitAllUrl.getUrls().forEach(url -> registry.antMatchers(url).permitAll());
        registry.antMatchers("/booking/listBooking").permitAll();
        registry.anyRequest().fullyAuthenticated();
    }



    @Bean
    public TokenStore tokenStore() {
        return new JwtTokenStore(accessTokenConverter());
    }

    /**
     * JwtAccessTokenConverter 实现了
     * TokenEnhancer 接口， 负责将普通UUID token增强为 JWT token
     * AccessTokenConverter 接口, 实际上是委托 DefaultAccessTokenConverter 实现token信息转换，token 《》map 相互转换
     * @return
     */
    @Bean
    public JwtAccessTokenConverter accessTokenConverter() {
        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        ((DefaultAccessTokenConverter)converter.getAccessTokenConverter()).setUserTokenConverter(new JwtUserAuthenticationConverter());
        converter.setSigningKey("123");
        return converter;
    }

    @Bean
    @Primary
    public DefaultTokenServices tokenService() {
        DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
        defaultTokenServices.setTokenStore(tokenStore());
        return defaultTokenServices;
    }

}
